import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const useMobileStore = defineStore('mobile', () => {
  const mobile = ref(null);
  const loading = ref(false);

  const setMobile = (value) => {
    mobile.value = value || {};
  };
  
  const getMobile = async() => {
    if (mobile.value != null) {
      return mobile.value;
    } else {
      return await loadMobile();
    }
  };

  const loadMobile = async() => {
    if (mobile.value != null) {
      loading.value = false;
      return mobile.value;
    }

    if (loading.value) {
      await sleep(100);
      return await loadMobile();
    }

    loading.value = true;
    if (mobile.value != null) {
      loading.value = false;
      return mobile.value;
    } else {
      const urlParams = new URLSearchParams(window.location.search);
      const mobileId = urlParams.get('mobileId');
      
      loading.value = true;
      const res = await api.post('/mobile/queryBy', {id: mobileId});
      loading.value = false;
      if (res.code === '1') {
        setMobile(res.data);
        return mobile.value;
      }
    }
  };
  
  const getPage = async(id) => {
    const mobile = await getMobile();
    if (!mobile 
        || !mobile.pageList 
        || mobile.pageList.length === 0) {
      return;
    }

    return mobile.pageList.find(page => page.id === id);
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return {
    getMobile,
    getPage
  };
});